package com.shicijiaoliu.interceptors;

import com.shicijiaoliu.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.shicijiaoliu.utils.ThreadLocalUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class logininterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {//options直接放行
            return true;
        }


        String  token = request.getHeader("Authorization"); //请求头名称:Authorization
        if(JWTUtil.verify(token) && !JWTUtil.isExpired(token)){
            Map<String,Object> claims = JWTUtil.getHeaderByBase64(token);
            ThreadLocalUtils.set(claims); //业务数据存到threadlocal
            return true;
        }else {
            response.setStatus(401);
            return false;}
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除业务数据
        ThreadLocalUtils.remove();
    }
}
